package common;

import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.sun.syndication.feed.synd.SyndCategory;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class RssParser {
	public static void parse() {
		parse("http://www.oschina.net/news/rss");
	}
	public static void parse(String sUrl) {
		String rss = sUrl;
		try {
			URL url = new URL(rss);
			// 读取Rss源
			XmlReader reader = new XmlReader(url);
			//System.out.println("Rss源的编码格式为：" + reader.getEncoding());
			SyndFeedInput input = new SyndFeedInput();
			// 得到SyndFeed对象，即得到Rss源里的所有信息
			SyndFeed feed = input.build(reader);
			// 得到Rss新闻中子项列表
			List entries = feed.getEntries();
			// 循环得到每个子项信息
			String querySql="select count(1) counts from rss_info where title=? and pubdate=?";
			String sql="insert into rss_info (title,link,value,pubdate,author,category,pub_flag) values (?,?,?,?,?,?,?)";
			
			List<Object> params = new ArrayList<Object>();
			Object[] obj=new Object[2];
			for (int i = 0; i < entries.size(); i++) {
				params.clear();
				//System.err.println(i);
				SyndEntry entry = (SyndEntry) entries.get(i);
				Timestamp pubdate=CommonUtil.dateTimeParser(entry.getPublishedDate().toString());
				if(pubdate.before(CommonUtil.getDate())){//如果新闻发布时间早于今天
					break;
				}
				// 标题、连接地址、标题简介、时间是一个Rss源项最基本的组成部分
				//System.out.println("标题：" + entry.getTitle());
				//System.out.println("连接地址：" + entry.getLink());
				SyndContent description = entry.getDescription();
				//System.out.println("标题简介：" + description.getValue());
				//System.out.println("发布时间：" + CommonUtil.dateParser(entry.getPublishedDate().toString()));
				// 以下是Rss源可先的几个部分
				//System.out.println("标题的作者：" + entry.getAuthor());
				
				//判断该记录存在与否
				obj[0]=entry.getTitle();
				obj[1]=pubdate;
				int row=DbUtil.getJdbcTemplate().queryForInt(querySql, obj);
				if(row>0)
					break;
			
				params.add(entry.getTitle());
				params.add(entry.getLink());
				params.add(description.getValue());				
				params.add(pubdate);
				params.add(entry.getAuthor());
				// 此标题所属的范畴
				List categoryList = entry.getCategories();
				if (categoryList != null) {
					if(categoryList.size()>=1){
						SyndCategory category = (SyndCategory) categoryList.get(0);
						//System.out.println("此标题所属的范畴：" + category.getName());
						params.add(category.getName());
					}else {
						params.add("");
					}
				}else {
					params.add("");
				}
				params.add("N");
				DbUtil.getJdbcTemplate().update(sql,params.toArray());

				// 得到流媒体播放文件的信息列表
				/*List enclosureList = entry.getEnclosures();
				if (enclosureList != null) {
					for (int n = 0; n < enclosureList.size(); n++) {
						SyndEnclosure enclosure = (SyndEnclosure) enclosureList.get(n);
						System.out.println("流媒体播放文件：" + entry.getEnclosures());
					}
				}*/
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static String getNews() {
		String sql="SELECT title,link from rss_info where pubdate>? and pub_flag='N' order by pubdate desc limit 1";
		String updateSql="update rss_info set pub_flag='Y' where pubdate>? and title=?";
		
		List<Object> params = new ArrayList<Object>();
		params.add(CommonUtil.getDate());
		
		List list=DbUtil.getJdbcTemplate().queryForList(sql, params.toArray());
		
		String title="";
		String link="";
		if(list.size()==1){
			Map map = (Map) list.get(0);
			title=map.get("title")==null?"":map.get("title").toString();
			link=map.get("link")==null?"":map.get("link").toString();
		}	
		params.add(title);
		DbUtil.getJdbcTemplate().update(updateSql,params.toArray());
		
		if(!StringUtils.isBlank(link ))
			title="<a href='"+link+"' target='_blank'>"+title+"</a>";
		else {
			return "";
		}
		return title;
	}
	
	public static String getNews1() {
		String sql="SELECT title,link from rss_info where pubdate>? and pub_flag='N' order by pubdate desc limit 1";
		String updateSql="update rss_info set pub_flag='Y' where pubdate>? and title=?";
		
		List<Object> params = new ArrayList<Object>();
		params.add(CommonUtil.getDate());
		
		List list=DbUtil.getJdbcTemplate().queryForList(sql, params.toArray());
		
		String title="";
		String link="";
		if(list.size()==1){
			Map map = (Map) list.get(0);
			title=map.get("title")==null?"":map.get("title").toString();
			link=map.get("link")==null?"":map.get("link").toString();
		}	
		params.add(title);
		DbUtil.getJdbcTemplate().update(updateSql,params.toArray());
		
		if(!StringUtils.isBlank(link ))
			title="<a href='"+link+"' target='_blank'>"+title+"</a>";
		else {
			return "";
		}
		return title;
	}
}
